/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.activity;

import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.explorer.ExplorerManager;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.TopComponent;
import pt.iasd.youthshelter.activity.nodes.ActivityChildren;
import pt.iasd.youthshelter.activity.nodes.RootNode;
import pt.iasd.youthshelter.datamodel.Activity;
import pt.iasd.youthshelter.datamodel.service.ActivityController;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//pt.iasd.youthshelter.activity//ActivityList//EN",
        autostore = false)
@TopComponent.Description(
        preferredID = "ActivityListTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "explorer", openAtStartup = true)
//@ActionID(category = "Window", id = "pt.iasd.youthshelter.activity.ActivityListTopComponent")
//@ActionReference(path = "Menu/Window" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_ActivityListAction",
        preferredID = "ActivityListTopComponent")
@Messages({
    "CTL_ActivityListAction=Activities"/*,
    "CTL_ActivityListTopComponent=Activities",
    "HINT_ActivityListTopComponent=List of registered activities."*/
})
public final class ActivityListTopComponent extends TopComponent implements ExplorerManager.Provider {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/activity/Bundle");
    private static final ExplorerManager explorerManager = new ExplorerManager();

    public ActivityListTopComponent() {
        initComponents();
        (new ActivityListWorker()).execute();
        setName(NbBundle.getMessage(ActivityListTopComponent.class, "ActivityListTopComponent.Title"));
        setToolTipText(NbBundle.getMessage(ActivityListTopComponent.class, "ActivityListTopComponent.Hint"));
        putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
        putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
    }
    
    public void refreshList() {
        (new ActivityListWorker()).execute();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ActivityListScrollPane = new javax.swing.JScrollPane();
        ActivityListView = new org.openide.explorer.view.ListView();

        ActivityListScrollPane.setViewportView(ActivityListView);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ActivityListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ActivityListScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane ActivityListScrollPane;
    private org.openide.explorer.view.ListView ActivityListView;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // add custom code on component closing
    }

    private void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // store your settings
    }

    private void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // read your settings according to their version
    }

    @Override
    public ExplorerManager getExplorerManager() {
        return explorerManager;
    }
    
    private class ActivityListWorker extends SwingWorker<List<Activity>, String> {
        ProgressHandle pHandle = ProgressHandleFactory.createHandle(bundle.getString("ProgressBarLoad"));
            
        @Override
        protected List<Activity> doInBackground() throws Exception {
            List<Activity> activities = null;
            
            pHandle.start();
            ActivityController controller = Lookup.getDefault().lookup(ActivityController.class);
            if(controller != null) {
                try{
                    activities = controller.findCurrentActivityEntities();
                } catch(Exception ex) {
                    Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
                    pHandle.finish();
                }
            }
            return activities;
        }

        @Override
        protected void done() {
            try {
                explorerManager.setRootContext(new RootNode(new ActivityChildren(get())));
            } catch (InterruptedException | ExecutionException ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            } finally {
                pHandle.finish();
            }
        }
    }
}
